const user = require('koa-router')()
const models = require('../models')

user
	.post('/add', async ctx => {
		try {
			const { name, age, sex } = ctx.request.body
			if (!name) {
				ctx.body = {
					code: 400,
					msg: '姓名不能为空'
				}
			} else if (!age) {
				ctx.body = {
					code: 400,
					msg: '年龄不能为空'
				}
			} else if (!sex) {
				ctx.body = {
					code: 400,
					msg: '性别不能为空'
				}
			} else {
				let result = await models.userModel.save({ name, age, sex })
				if (result) {
					ctx.body = {
						code: 200,
						msg: '请求成功',
						success: true
					}
				} else {
					ctx.body = {
						code: 400,
						success: false
					}
				}
			}
		} catch (error) {
			ctx.status = 500
			ctx.body = {
				msg: '服务器异常'
			}
		}
	})
	.get('/find', async ctx => {
		try {
			let name = ctx.query.name
			let data = name ? { name } : {}
			let result = await models.userModel.find(data)

			ctx.body = {
				code: 200,
				data: result,
				msg: '请求成功',
				success: true
			}
		} catch (error) {
			ctx.body = {
				code: 500,
				msg: '服务器异常'
			}
		}
	})
	.get('/findone', async ctx => {
		let name = ctx.query.name

		if (!name) {
			ctx.body = {
				code: 400,
				msg: '查询参数不能为空'
			}
		} else {
			try {
				let result = await models.userModel.find({ name })

				ctx.body = {
					code: 200,
					data: result,
					msg: '请求成功',
					success: true
				}
			} catch (error) {
				ctx.body = {
					code: 500,
					msg: '服务器异常'
				}
			}
		}
	})
	.get('/findbyid', async ctx => {
		try {
			let id = ctx.query.id
			let result = await models.userModel.findById({ _id: id })
			ctx.body = {
				code: 200,
				data: result,
				msg: '请求成功',
				success: true
			}
		} catch (error) {

		}
	})

module.exports = user